package com.stylefeng.guns.core.node;

import java.util.ArrayList;
import java.util.List;

/***
 * add by 张亚林
 * @Date 2018-09-28
 */
public class List2ZTree {
  
  /** * 方式一：使用两层循环实现 * @param list * @return */

  public static List<ZTreeNode> toTree01(List<ZTreeNode> treeList) {
    List<ZTreeNode> retList = new ArrayList<>();
    for (ZTreeNode parent : treeList) {
      if ("0".equals(parent.getPId())) {
        retList.add(parent);
      }
      for (ZTreeNode child : treeList) {
        if (child.getPId() == parent.getId()) {
          if (parent.getChildren() == null) {
            parent.setChildren(new ArrayList<>());
          }
          parent.getChildren().add(child);
        }
      }
    }
    return retList;
  }
  /** * 方式二：使用递归实现 * @param treeList * @return */

  public static List<ZTreeNode> toTree02(List<ZTreeNode> treeList) {
    List<ZTreeNode> retList = new ArrayList<>();
    for (ZTreeNode parent : treeList) {
      if (0l==parent.getPId()) {
        retList.add(findChildren(parent, treeList));
      }
    }
    return retList;
  }

  private static ZTreeNode findChildren(ZTreeNode parent, List<ZTreeNode> treeList) {
    for (ZTreeNode child : treeList) {
      if (parent.getId().equals(child.getPId())) {
        if (parent.getChildren() == null) {
          parent.setChildren(new ArrayList<>());
        }
        parent.getChildren().add(findChildren(child, treeList));
      }
    }
    return parent;
  }
}
